import { createStore } from 'vuex'

// Todo 类型注解
export type Todo = {
  id: number;
  content: string;
  completed: boolean;
};

// Status 类型注解
export type Status = 'all' | 'active' | 'completed';

// 创建仓库实例
const store = createStore({
  state: {
    // 数据初始化时 - 获取本地存储数据
    list: JSON.parse(localStorage.getItem('todos-list') || '[]') as Todo[],
    status: localStorage.getItem('todos-status') || 'all' as Status
  },
  mutations: {
    // 4. 主体 - 根据 id 删除数据
    delById (state, id: number) {
      state.list = state.list.filter((v) => v.id !== id)
    },
    // 5. 主体 - 根据 id 更新完成状态
    changeDone (state, id: number) {
      const index = state.list.findIndex((v) => v.id === id)
      state.list[index].completed = !state.list[index].completed
    },
    // 6. 底部 - 删除已完成任务
    clearDone (state) {
      state.list = state.list.filter((v) => !v.completed)
    },
    // 8. 底部 - 高亮切换效果
    changeStatus (state, status: Status) {
      state.status = status
    },
    // 10. 头部 - 双向数据绑定，按回车键，新增待办任务
    addTodo (state, todo: Todo) {
      state.list.unshift(todo)
    },
    // 11. 主体 - 计算全选状态，切换全选状态
    changeAll (state, checked) {
      state.list = state.list.map(item => ({ ...item, completed: checked }))
    }
  },
  getters: {
    // 计算剩余任务数量
    leftCount (state) {
      return state.list.filter(v => !v.completed).length
    }
  }
})

// 默认导出仓库
export default store

// 导出 TodoState 类型注解
export type TodoState = typeof store.state
